package com.example.base.net

import com.blankj.utilcode.util.SPUtils
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

class RetrofitUtils {
    //线程安全的单例网络请求
    companion object{
        @Volatile
        private var instance:RetrofitUtils? = null

        fun getInstance():RetrofitUtils{
            if(instance==null){
                synchronized(this){
                    if(instance==null){
                        instance = RetrofitUtils()
                    }
                }
            }
            return instance!!
        }
    }

    fun getRetrofit():Retrofit{
        var client = OkHttpClient.Builder()
            .readTimeout(5,TimeUnit.SECONDS)
            .writeTimeout(5,TimeUnit.SECONDS)
            .connectTimeout(5,TimeUnit.SECONDS)
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .addInterceptor {
                val token = SPUtils.getInstance().getString("token")
                val request = it.request().newBuilder()
                    .addHeader("Authori-zation", "521804d468ff441ba576e79492658ddc").build()
                it.proceed(request)
            }
            .retryOnConnectionFailure(true)//当请求失败时进行重试  但只能重新连接一次
            .proxy(Proxy.NO_PROXY)//解决部分抓包问题
            .build()
        var retrofit = Retrofit.Builder()
            .client(client)
            .baseUrl(Cons.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return retrofit
    }
}